#!/usr/bin/env bash
set -euo pipefail

API_BASE_URL="${API_BASE_URL:-http://127.0.0.1:8080}"
ADMIN_EMAIL="${ADMIN_EMAIL:-admin@example.com}"
ADMIN_PASSWORD="${ADMIN_PASSWORD:-Admin@1234}"
USER_EMAIL="${USER_EMAIL:-demo_user@example.com}"
USER_PASSWORD="${USER_PASSWORD:-User@1234}"

ADMIN_COOKIE_FILE="$(mktemp)"
USER_COOKIE_FILE="$(mktemp)"

cleanup() {
  rm -f "${ADMIN_COOKIE_FILE}" "${USER_COOKIE_FILE}"
}
trap cleanup EXIT

echo "[1/7] Admin login..."
curl -sS -c "${ADMIN_COOKIE_FILE}" -X POST "${API_BASE_URL}/auth/login" \
  -H "Content-Type: application/json" \
  -d "{\"email\":\"${ADMIN_EMAIL}\",\"password\":\"${ADMIN_PASSWORD}\"}" > /tmp/admin_login.json

if ! grep -q "access_token" /tmp/admin_login.json; then
  echo "Admin login failed:"
  cat /tmp/admin_login.json
  exit 1
fi

echo "[2/7] Create script..."
SCRIPT_PAYLOAD='{
  "name": "Demo Strategy",
  "symbol": "ETH-USDT",
  "market_type": "perpetual"
}'

curl -sS -b "${ADMIN_COOKIE_FILE}" -X POST "${API_BASE_URL}/scripts" \
  -H "Content-Type: application/json" \
  -d "${SCRIPT_PAYLOAD}" > /tmp/script_create.json

WEBHOOK_URL=$(python - <<'PY'
import json
import sys
data=json.load(sys.stdin)
print(data["webhook_url"])
PY
< /tmp/script_create.json)

BODY_SECRET=$(python - <<'PY'
import json
import sys
data=json.load(sys.stdin)
print(data["body_secret"])
PY
 < /tmp/script_create.json)

SCRIPT_ID=$(python - <<'PY'
import json
import sys
data=json.load(sys.stdin)
print(data["id"])
PY
 < /tmp/script_create.json)

if [ -z "${WEBHOOK_URL}" ]; then
  echo "Failed to create script:"
  cat /tmp/script_create.json
  exit 1
fi

echo "  Webhook URL: ${WEBHOOK_URL}"
echo "  Body secret: ${BODY_SECRET}"

echo "[3/7] Register demo user..."
curl -sS -X POST "${API_BASE_URL}/auth/register" \
  -H "Content-Type: application/json" \
  -d "{\"email\":\"${USER_EMAIL}\",\"password\":\"${USER_PASSWORD}\",\"role\":\"user\"}" > /tmp/user_register.json || true

echo "[4/7] User login..."
curl -sS -c "${USER_COOKIE_FILE}" -X POST "${API_BASE_URL}/auth/login" \
  -H "Content-Type: application/json" \
  -d "{\"email\":\"${USER_EMAIL}\",\"password\":\"${USER_PASSWORD}\"}" > /tmp/user_login.json

echo "[5/7] Subscribe user to script..."
curl -sS -b "${USER_COOKIE_FILE}" -X POST "${API_BASE_URL}/subscriptions" \
  -H "Content-Type: application/json" \
  -d '{
    "script_id": '"${SCRIPT_ID}"',
    "enabled": true,
    "allocation": {"mode": "fixed_quote", "value": 100},
    "connector_name": "gate_io_perpetual",
    "account_name": "'"${USER_EMAIL}"'"
  }' > /tmp/subscription.json

echo "[6/7] Send simulated TradingView signal..."
NONCE=$(date +%s%N)
curl -sS -X POST "${API_BASE_URL}${WEBHOOK_URL}" \
  -H "Content-Type: application/json" \
  -d "{
    \"secret\": \"${BODY_SECRET}\",
    \"nonce\": \"${NONCE}\",
    \"trade_type\": \"BUY\",
    \"order_type\": \"MARKET\",
    \"position_action\": \"OPEN\",
    \"symbol\": \"ETH-USDT\",
    \"price\": 3200,
    \"target\": {\"mode\": \"fixed_quote\", \"value\": 100}
  }" > /tmp/webhook.json

echo "Signal response:"
cat /tmp/webhook.json
echo

sleep 2

echo "[7/7] Fetch snapshots..."
echo "Recent signals:"
curl -sS -b "${ADMIN_COOKIE_FILE}" "${API_BASE_URL}/webhooks/tv/recent-signals"
echo
echo "User orders snapshot:"
curl -sS -b "${USER_COOKIE_FILE}" "${API_BASE_URL}/orders/snapshot"
echo

echo "Quick test completed."
